package cn.tedu.carhome.service.impl;

import cn.tedu.carhome.ex.ServiceException;
import cn.tedu.carhome.mapper.StockMapper;
import cn.tedu.carhome.mapper.SupplierMapper;
import cn.tedu.carhome.mapper.UserMapper;
import cn.tedu.carhome.pojo.VO.DrugVO;
import cn.tedu.carhome.pojo.VO.StockHeadVO;
import cn.tedu.carhome.pojo.dto.InsertStockDTO;
import cn.tedu.carhome.pojo.dto.InsertStockHeadDTO;
import cn.tedu.carhome.pojo.entity.Drug;
import cn.tedu.carhome.pojo.entity.User;
import cn.tedu.carhome.service.AddStockService;
import cn.tedu.carhome.web.State;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddStockServiceImpl implements AddStockService {
    @Autowired(required = false)
    StockMapper stockMapper;
    @Autowired
    SupplierMapper supplierMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public void addStock( InsertStockHeadDTO insertStockHeadDTO) {
        System.out.println(insertStockHeadDTO.getId());
        //verifier:审核人
        User user = userMapper.selectByUsername(insertStockHeadDTO.getVerifier());
        if (user==null){
            //异常
            throw new ServiceException(State.ERR_USER_NOT_DUPLICATE,"审核人不存在");
        }
        //通过verifier查找用户的id
        insertStockHeadDTO.setVerifierId(user.getId());
        //添加入库单
        stockMapper.insertStockHead(insertStockHeadDTO);

        List<InsertStockDTO> list = insertStockHeadDTO.getStockIn();
        for(InsertStockDTO insertStockDTO:list){
            DrugVO  drug = stockMapper.selectDrugById(insertStockDTO.getDrugId());
            if(drug!=null){//判断drugId是否已经存在
                //抛出异常
                throw new ServiceException(State.ERR_DRUG_ID_DUPLICATE,"药品编码已存在");
            }
            //插入药品
            stockMapper.insertDrug(insertStockDTO);
            //通过入库人员来查入库单单头的id
            StockHeadVO stockHeadVO = stockMapper.selectStockHeadByPerson(insertStockHeadDTO.getPerson());
            insertStockDTO.setStockId(stockHeadVO.getId());
            //插入入库单单目
            stockMapper.insertStockIn(insertStockDTO);
        }
        if (supplierMapper.supplierSelectByName(insertStockHeadDTO.getSupplierName()) ==null){
            //表示供货商不存在
            //抛异常
            throw new ServiceException(State.ERR_SUPPLIER_NOT_DUPLICATE,"供货商不存在");
        }


        System.out.println("添加完成");
    }

}
